import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { StorageUtil } from '../utils/storage.util';
import { LoadingServer } from '../common/loading/loading.server';

@Injectable({
  providedIn: 'root'
})

/**
 * @author leihfei
 * @date 2019-04-01
 * @description http请求客户端服务
 */
export class HttpService {

  constructor(private http: HttpClient, private loading: LoadingServer) {
  }


  /**
   * 响应头
   */
  private httpOptions(): any {
    return {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': this.checkAuth()
      })
    };
  }


  /**
   * token校验
   */
  private checkAuth(): string {
    const token = StorageUtil.getLocalStorage('token');
    return token ? token : '';
  }

  /**
   * 响应头2
   */
  private httpOptions2(): any {
    return new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': this.checkAuth()
    });
  }

  /**
   * @author leihfei
   * @date 2019-04-03
   * @description 发送http POST请求 登录
   */
  login(data: any, url: string, state: boolean = true): Observable<any> {
    if (state) {
      this.loading.load();
    }
    return this.http.post<any>(url, data, {headers: {'Content-Type': 'application/json'}});
  }

  /**
   * @author leihfei
   * @date 2019-04-03
   * @description 发送http POST请求
   */
  post(data: any, url: string, state: boolean = true): Observable<any> {
    if (state) {
      this.loading.load();
    }
    return this.http.post<any>(url, data, this.httpOptions());
  }

  /**
   * @author leihfei
   * @date 2019-04-03
   * @description 发送http POST请求 文件七牛
   */
  postFile(data: any, url: string, state: boolean = true): Observable<any> {
    if (state) {
      this.loading.load();
    }
    return this.http.post<any>(url, data, {
      headers: new HttpHeaders({
        'Authorization': this.checkAuth()
      })
    });
  }

  /**
   * @author leihfei
   * @date 2019-04-03
   * @description 发送http GET请求
   */
  get(param: any, url: string, state = false): Observable<any> {
    if (state) {
      this.loading.load();
    }
    return this.http.get(url, this.httpParams(param));
  }


  /**
   * @author leihfei
   * @date 2019-04-03
   * @description 将get请求中的对象处理成httpParams对象
   */
  private httpParams(param: any): any {
    // 循环对象，将值处理成http请求的方式
    const temp = {};
    Object.keys(param).forEach(key => {
      if (param[key] instanceof Object) {
        return;
      }
      // 判断传输的类型是否为字符串
      let value;
      if (typeof param[key] === 'number') {
        value = param[key];
      } else {
        value = param[key].trim();
      }
      if (value || (value === 0)) {
        temp[key] = value;
      }
    });
    const options = {
      params: new HttpParams({
        fromObject: temp
      }),
      headers: this.httpOptions2()
    };
    return options;
  }
}
